var switchAccount201902Cofig = {};
/**
 * 加载切换身份.
 */
var zxmArr=new Array();
var curUid=0;
var myUid=0;
function loadSwitchAccount(){
	if(switchAccount201902Cofig.datas != undefined){
		return;
	}
	var eleId = "switchAccountContainer201902"; 
	var html=''; 
	var html2=''; 
	var dataJson = getFormValue("myForm");
	/////////////////↓↓↓询中需要修改的地方：配置请求的apiUrl
	dataJson.apiUrl = "userAccountBind/getMyAccounts";//,cache:true,debug:true
	ajaxForSelect(dataJson,function(rs){
		var datas = rs.datas;
		switchAccount201902Cofig.datas = datas;
		var size = datas.length;
		curUid=rs.curUid;
		//2021-4-9 改版 直接展示下拉
		var size = datas.length;
		var accountTypeDesc;
		var ptmap={"company":1,"subAdmin":2,"projectGroup":3,"bkgnd":4};
		var stArr=new Array(),saArr=new Array(),ttArr=new Array(),nowData={},subAdminData={},projectData={},isPerKz=0;
		for(var i=0;i<size;i++){
			var d = datas[i];
			if(rs.curUid == d.targetUid){
				if(ttArr.indexOf(d.accountTypeDesc)==-1){
					ttArr.push(d.accountTypeDesc);
					nowData=d;
					if(d.accountTypeDesc=='subAdmin'||d.accountTypeDesc=='company'){
						subAdminData=d;
						subAdminData.index=i;
					}else if(d.accountTypeDesc=='projectGroup'){
						projectData=d;
						projectData.index=i;
					}
				}
			}
			if(d.targetUid==0){
				isPerKz=1;
				continue;
			}
			if(stArr.indexOf(d.targetUid)==-1){
				stArr.push(d.targetUid);
				d.index=i;
				saArr.push(d);
			}else{
				var ind=stArr.indexOf(d.targetUid);
				if(ptmap[d.accountTypeDesc]<ptmap[saArr[ind].accountTypeDesc]){
					stArr.splice(ind,1);
					saArr.splice(ind,1);
					stArr.push(d.targetUid);
					d.index=i;
					saArr.push(d);
				}
			}
			if(zxmArr.indexOf(d.targetUid)==-1&&d.accountBindId==2&&(d.accountType==-1||d.accountType==-2)&&d.accountTypeDesc=='projectGroup'){
				zxmArr.push(d.targetUid);
			}
		}
		size=saArr.length;
		for(var i=0;i<size;i++){
			var d = saArr[i];
			accountTypeDesc = d.accountTypeDesc ;
			if(d.name == undefined){
				d.name = "未填写";
			}
			var skname='';
			if(d.name.split("-").length>2){
				for(var t=0;t<d.name.split("-").length-1;t++){
					skname+=d.name.split("-")[t];
				}
			}else{
				skname=d.name.split("-")[0];
			}
			if(nowData.targetUid==d.targetUid){
				nowData.name=skname;
			}
			if(typeClient==1){
				html += '<span onclick="switchAccount201902('+d.myUid+','+d.targetUid+','+d.accountBindId+","+d.index+')">'+skname+'</span>';
			}else{
				html+='<li ><a onclick="switchAccount201902('+d.myUid+','+d.targetUid+','+d.accountBindId+","+d.index+')">'+skname+'</a></li>';
			}
		}
		myUid=nowData.myUid;
		if(ttArr.indexOf('personal')>-1){
			if(typeClient==1){
				html2+='<span onclick="gotoPage(\'cpq\')">个人测评</span>';
				if(isAdmin==1&&isPerKz==1){
					html2+='<span onclick="gotoPage(\'admin\')">平台管理</span>';
				}
			}else{
				html2+='<li><a href="cpq">个人测评</a></li>';
				if(isAdmin==1&&isPerKz==1){
					html2+='<li><a href="admin">平台管理</a></li>';
				}
			}
		}else{
			//"company":1,"subAdmin":2,"projectGroup":3,"bkgnd":4
			//typeClient 1.个人前台  2.后台 
			if(ttArr.indexOf('company')>-1||ttArr.indexOf('subAdmin')>-1){
				if(typeClient==1){
					if(ttArr.indexOf('projectGroup')>-1){
						html2+='<span onclick="switchAccount201902('+subAdminData.myUid+','+subAdminData.targetUid+','+subAdminData.accountBindId+","+subAdminData.index+')">科学用人系统</span>';
					}else{
						html2+='<span onclick="gotoPage(\'cpq\')">科学用人系统</span>';
					}
				}else{
					if(ttArr.indexOf('projectGroup')>-1){
						html2+='<li><a onclick="switchAccount201902('+subAdminData.myUid+','+subAdminData.targetUid+','+subAdminData.accountBindId+","+subAdminData.index+')">科学用人系统</a></li>';
					}else{
						html2+='<li><a href="cpq">科学用人系统</a></li>';
					}
				}
				if(ttArr.indexOf('company')>-1&&isAdmin==1){
					if(typeClient==1){
						//html2+='<span onclick="changeClientType(-1)">CRM控制面板</span>';
						html2+='<span onclick="dealerPwd(1,-1)">CRM控制面板</span>';
					}else{
						html2+='<li><a onclick="changeClientType(-1)">CRM控制面板</a></li>';
						//html2+='<li><a onclick="dealerPwd(1,-1)">CRM控制面板</a></li>';
					}
				}
				$(".syBackstageMan").attr("onclick","gotoPage('cpq')");
			}
			if(ttArr.indexOf('bkgnd')>-1){
				if(typeClient==1){
					//html2+='<span onclick="changeClientType('+rs.curUid+')">CRM系统</span>';
					html2+='<span onclick="dealerPwd(1,'+rs.curUid+')">CRM系统</span>';
				}else{
					html2+='<li><a onclick="changeClientType('+rs.curUid+')">CRM系统</a></li>';
				}
				if(!(ttArr.indexOf('company')>-1||ttArr.indexOf('subAdmin')>-1||ttArr.indexOf('projectGroup')>-1)){
					$(".syBackstageMan").attr("onclick","gotoPage('admin')");
				}
			}
			if(ttArr.indexOf('projectGroup')>-1){
				if(typeClient==1){
					html2+='<span onclick="switchAccount201902('+projectData.myUid+','+projectData.targetUid+','+projectData.accountBindId+","+projectData.index+')">咨询师交付系统</span>';
				}else{
					html2+='<li><a onclick="switchAccount201902('+projectData.myUid+','+projectData.targetUid+','+projectData.accountBindId+","+projectData.index+')">咨询师交付系统</a></li>';
				}
				if(!(ttArr.indexOf('company')>-1||ttArr.indexOf('subAdmin')>-1)){
					$(".syBackstageMan").attr("onclick","gotoPage('home/companyu/project/ucenter_serviceItems')");
				}
			}
		}
		$(".comAccList").html(html);
		if(typeClient==1){
			$(".typeAccList").prepend(html2);
			$(".chooseType").show();
		}else{
			var nowCheckType=($.cookie('fe'+curUid+'-'+myUid)==undefined?rs.curUid:$.cookie('fe'+curUid+'-'+myUid));
			if(ttArr.indexOf('personal')>-1){
				nowCheckType=0;
			}
			$(".typeAccList").html(html2);
			$("#drop3 font").html(nowData.name).attr("data-companyUid",ttArr.indexOf('personal')>-1?0:rs.curUid);
			$("#drop4 font").html(ttArr.indexOf('personal')>-1?'平台管理':(nowCheckType==-1?'CRM控制面板':'CRM系统'));
			if(nowCheckType==-1){
        		initMenu({menuKey:"dealer"});
        	}else{
        		initMenu({companyUid:nowCheckType});
        	}
        	if(typeof(window['loadingData']) === "function") {
				loadingData();
			}
		}
		
	},{isShow:false});
}
function changeClientType(companyUid){
	/*console.log(companyUid);
	return;*/
	$.cookie('fe'+curUid+'-'+myUid, '', { expires: -1 });
	$.cookie('fe'+curUid+'-'+myUid,companyUid,{expires: 1, path: '/'});
	gotoPage("admin");
}

function gotoRegCom(){
	if(typeof deuids !="undefined"){
		delCookie(deuids);
	}
	var rootPath = "login";
	var op = {};
	op.url = "root.json";
	jQuery.ajax({
		url:op.url
		,data:{action:"logout",os:"PC"}
		,type:"post"
		,dataType:"json"
		,timeout:10000
		,success:function(data){
		}
		,error:function(XMLHttpRequest, textStatus, errorThrown){
		}
		,complete:function(){
			window.parent.location.href = getBasePath()+"login?register=1&registerType=company";
		}
	});

}

function switchAccount201902(myUid,targetUid,accountBindId,index){
	var data = switchAccount201902Cofig.datas[index];
	var dataJson = {targetUid:targetUid,accountBindId:accountBindId,accountType:data.accountType,name:data.name};
	dataJson.apiUrl = "userAccountBind/switchAccount";//,cache:true,debug:true
	ajaxForUpdate(dataJson,function(rs){
		//切换成功.跳转页面.
		if(data.accountTypeDesc=='bkgnd'){
			gotoPage("admin");
		}else if(data.accountTypeDesc=='projectGroup'){
			gotoPage("home/companyu/project/ucenter_serviceItems");
		}else{
			gotoPage("cpq");
		}
	},{msg:"切换成功"});
}

function switchAccountSetMainAccount201902(myUid,targetUid){
	var eleId = "switchAccountContainer201902"; 
	var dataJson = {targetUid:targetUid,isMainAccount:1};
	dataJson.apiUrl = "userAccountBind/setMainAccount";//,cache:true,debug:true
	ajaxForUpdate(dataJson,function(rs){
		$("#"+eleId).remove();
		loadSwitchAccount();
	},{msg:"设置成功"});
}



/**
 * 加载设置管理员.
 */
function loadSwitchAccountSetAdmin(){
	var dataJson = {apiUrl:"userAccountBind/getCurAdminAccountMsg"};
	var html=''; 
	ajaxForSelect(dataJson,function(rs){
		if(rs.phoneNumber == "" || rs.phoneNumber == undefined){
			showMsg("使用个人手机号登录的才能变更管理员","error");
			return;
		}
		html += '﻿<div class="notice" >'; 
		html += '    <div class="windowpop kind8">'; 
		html += '        <h1>变更主管理员<img onclick="$(this).parent().parent().parent().remove();" class="fr" src="images/newBackstageIcon/windowPopClose@2x.png" alt="" /></h1>'; 
		html += '        <hr class="fullHr">'; 
		html += '        <p>*换绑主管理员账号时，需要验证当前管理员的身份</p>'; 
		html += '        <ul>'; 
		html += '            <li><span>当前绑定账号:</span><i>'+(rs.name==undefined?'未填写':rs.name)+'</i></li>';
		html += '            <li><span>手机号:</span><input type="text" placeholder="" readonly="readonly" value="+'+rs.smsCountryCode+"  "+rs.phoneNumber+'"></li>'; 
		html += '            <li><span>验证码:</span><p><em  class="conum" onclick="setAdminGetAuthCode201902(this,1)">获取验证码</em><input id="mainAccountAuthCode2019092" type="text" placeholder="输入验证码"></p></li>'; 
		html += '        </ul>'; 
		html += '        <menu onclick="setAdminNext201909(this)">下一步</menu>'; 
		html += '    </div>'; 
		html += '</div>'; 
		$('body').append(html);
	});
}

//<!--倒计时开始-->
var letgo201902 = true;
function setAdminGetAuthCode201902(obj,step){
	if(!letgo201902){
		return;
	}
	
	var dataJson = {};
	if(step == 1){
		dataJson.apiUrl = "userAccountBind/getAuthCodeForAdmin";
	}else{
		dataJson.apiUrl = "userAccountBind/getAuthCodeByUid";
		dataJson.targetUid = switchAccount201902Cofig.targetUid;
	}
    
	ajaxForUpdate(dataJson,function(rs){
		var time = 60,
        $this = $(obj);
	    if(letgo201902){
	        letgo201902 = false;
	        $this.text(time+"s");
	        var timer= setInterval(function () {
	            $this.text(--time+'s');
	            if(!time){
	                clearInterval(timer);
	                $this.text('获取验证码');
	                letgo201902 = true;
	            }
	        },1000)
	    }
	},{msg:"验证码发送成功"});
};
//<!--倒计时结束-->

function setAdminNext201909(obj){
	var authCode = $("#mainAccountAuthCode2019092").val();
	if(authCode == ''){
		showMsg('请输入验证码');
		return;
	}
	var dataJson = {apiUrl:"userAccountBind/checkAuthCodeForAdmin",authCode:authCode};
	ajaxForSelect(dataJson,function(rs){
		switchAccount201902Cofig.authToken = rs.datas;
		//弹出下一个页面.
		letgo201902 = true;
		$(obj).parent().parent().remove();
		loadSwitchAccountSetAdminForNewAccount();
		addDeptSwitch(0);
	});
}

function loadSwitchAccountSetAdminForNewAccount(){

	var html=''; 
	html += '﻿<div class="notice">'; 
	html += '    <div class="windowpop kind8">'; 
	html += '        <h1>验证新管理员账号<img onclick="$(this).parent().parent().parent().remove();" class="fr" src="images/newBackstageIcon/windowPopClose@2x.png" alt=""></h1>'; 
	html += '        <hr class="fullHr">'; 
	html += '        <p>*换绑主管理员账号时，需要验证当前管理员的身份</p>'; 
	html += '        <ul>'; 
	html += '            <li>'; 
	html += '                <span>新主管理员姓名:</span>'; 
	html += '                <input id="switchAdminForSearchCompany201902" type="text" placeholder="在企业成员内搜索"  class="search" style="background:url(\'images/newBackstageIcon/searchlittlegray2x.png\') no-repeat 222px center">'; 
	html += '                <div>'; 
	html += '                </div>'; 
	html += '                <ol class="dropdown" id="dpdown">'; 
	html += '            	 </ol>'; 
	html += '            <li><span>手机号:</span><input id="switchAdminForPhoneNumber201902" type="text" placeholder="" readonly="readonly"></li>'; 
	html += '            <li><span>验证码:</span><p><em class="conum" onclick="setAdminGetAuthCode201902(this,2)">获取验证码</em><input id="mainAccountNewAuthCode2019092" type="text" placeholder="输入验证码"></p></li>'; 
	html += '        </ul>'; 
	html += '        <menu onclick="switchAccountSetAdminForNewAccountConfirm201902()">确定</menu>'; 
	html += '    </div>'; 
	html += '</div>'; 
	$('body').append(html);
	loadSwitchAccountSetAdminForNewAccountForEvent201902();
	downDemon();
}
/**
 * 添加部门.
 */
function addDeptSwitch(cpgid){
	if(cpgid == 0){
		$("#dpdown").html("");
	}
	var ds = {apiUrl:"company/getGroupForCompany",cpgid:cpgid,nosub:1};
	ajaxForSelect(ds,function(rs){
		var html = "";
		var datas = rs.datas.emps;
			var size = datas.length;
		if(cpgid == 0){
			html += '<li onclick="letouch(this)" class="le1" groupid="0" style="background:url(\'images/newBackstageIcon/yzdown@2x.png\') no-repeat left 10px;">';
		//	html += '<h2 onclick="letouch(this)">';		
			html += '<p>默认分组</p>';
		//	html += '</h2>';
			html += '<ol class="lev1">';
			for(var i=0;i<size;i++){
				var d = datas[i];
					html += '<li class="peole" >';
					if(d.subidd!=0){
						html += '<p style="text-decoration: line-through;color: #aeaeae;" >'+d.name+'</p>';			
					}else{
						html += '<p uid="'+d.uid+'" data-smsCountryCode='+d.smsCountryCode+' data-phoneNumber='+d.phoneNumber+'>'+d.name+'</p>';			
					}
					html += '</li>';		
			}		
			html += '</ol >';
			html += '</li>';	
		
			//load emp.

			//load dept.
			datas = rs.datas.list;
			size = datas.length;
			for(var i=0;i<size;i++){
				var d = datas[i];
				html += '	<li onclick="letouch(this)" class="le1" groupid="'+d.cpgid+'" id="groupidf'+d.cpgid+'" style="background:url(\'images/newBackstageIcon/yzdown@2x.png\') no-repeat left 10px;">';
				html += '	 <p>'+d.name+'</p>';
				html += '	 <ol></ol>';
				html += '</li>';
			}
			$("#dpdown").html(html);
			//addLevel1Event();
		}else{
			//load dept.
			
			var delist = rs.datas.list;
			var desize = datas.length;

			//load emp.
			var emplist = rs.datas.emps;
			var empsize = datas.length;

			for(var g=0;g<delist.length;g++){
					var d = delist[g];
				html += '	<li onclick="letouch(this)" class="le1" groupid="'+d.cpgid+'" id="groupidf'+d.cpgid+'" style="background:url(\'images/newBackstageIcon/yzdown@2x.png\') no-repeat left 10px;">';
				html += '	 <p>'+d.name+'</p>';
				html += '	 <ol></ol>';
				html += '</li>';
			}
			for(var t=0;t<emplist.length;t++){
			var d = emplist[t];
					html += ' <li class="peole" >';
					if(d.subidd!=0){
						html += '<p style="text-decoration: line-through;color: #aeaeae;" >'+d.name+'</p>';			
					}else{
					    html += '<p uid="'+d.uid+'" data-smsCountryCode='+d.smsCountryCode+' data-phoneNumber='+d.phoneNumber+'>'+d.name+'</p>';
					}
					html += '	</li>';
			}
			/*console.log(cpgid);
			console.log(html);
			console.log($("#groupidf"+cpgid).find("ol"));*/
			$("#groupidf"+cpgid).find("ol").html(html);
			
		}
		
		//touchli();
	},{isShow:false,async:false});

}
function letouch(e){
	 var groupid = $(e).attr("groupid");
	     var isShow = $(e).hasClass("up");
	     var runon = $(e).hasClass("runon");
	      if(!isShow&&groupid!=0&&!runon){
	     	addDeptSwitch(groupid);
	     	$(e).addClass("up runon");      
	     }
	      /*  var $this = $(e),
	            $ol = $this.siblings("ol"),
	            $ul = $this.siblings("ul");
	            
	            if(($ol.length && $ol.css("display") === "none") || ($ul.length && $ul.css("display") === "none")){
	                $this.addClass("up runon");      
	            }else{
	                $this.removeClass("up");
	            }
	            if($ol.length){
	                $ol.slideToggle(300);
	            }
	        	if($ul.length){
	            $ul.slideToggle(300);
	        	}*/
	
}
function downDemon(){
	$('#dpdown').click(function(e){
        var mytarget = e.target,
            $this = $(mytarget),
            $thisol =  $this.siblings('ol');
        if(mytarget!== this && $thisol.length>0){
             $thisol.toggle();
             $this.parent().toggleClass('yzup');
        }else if($(mytarget).prop("tagName") === "P" && !$this.parent().attr('style')){
            if($(mytarget).attr("data-phoneNumber")==null || $(mytarget).attr("data-phoneNumber")==""){
           	  showMsg("该成员已经是管理员，请选择其他成员","error");
  			       return;
            }else{
           	 $(this).hide();
            }
            $('.search').val($(mytarget).text());
            $('#switchAdminForPhoneNumber201902').val("+"+$(mytarget).attr("data-smsCountryCode")+"  "+$(mytarget).attr("data-phoneNumber"));
            switchAccount201902Cofig.targetUid = $(mytarget).attr("uid");      
         }
	});
    $('.search').on('focus',function(){
        $('#dpdown').show();
    })
}

function loadSwitchAccountSetAdminForNewAccountForEvent201902(){
	$('#switchAdminForSearchCompany201902').on('input',function () {
		$("#dpdown").hide();
		var that = this;
		$(this).siblings('div').append("");
		if($(this).val() == ''){
			$(this).siblings('div').slideUp();
		}else{
			$(this).siblings('div').slideDown();
			ajaxForSelect({apiUrl:"company/searchC8CompanyEmployee",name:$(that).val()},function(rs){
				var html=''; 
				var datas = rs.datas;
				var size = datas.length;
				for(var i=0;i<size;i++){
					var d = datas[i];
				 	html += '                    <p data-smsCountryCode="'+d.smsCountryCode+'" data-uid="'+d.uid+'"  data-phoneNumber="'+d.phoneNumber+'">'+d.name+'</p>'; 
				}
				$(that).siblings('div').html(html);
			},{isShow:false});
		}
    });
    $('#switchAdminForSearchCompany201902').siblings('div').click(function (e) {
        var $target = $(e.target);
        if($target !== this){
            $('#switchAdminForSearchCompany201902').val($target.text());
            $('#switchAdminForPhoneNumber201902').val("+"+$target.attr("data-smsCountryCode")+"  "+$target.attr("data-phoneNumber"));
            switchAccount201902Cofig.targetUid = $target.attr("data-uid");
            $(this).slideUp();
        }
    })
}


function switchAccountSetAdminForNewAccountConfirm201902(){
	var authCode = $("#mainAccountNewAuthCode2019092").val();
	if(authCode == ''){
		showMsg('请输入验证码');
		return;
	}
	var dataJson = {apiUrl:"userAccountBind/checkAuthCodeByUid",authCode:authCode};
	dataJson.targetUid = switchAccount201902Cofig.targetUid;
	dataJson.authToken = switchAccount201902Cofig.authToken;
	//console.log(dataJson);
	ajaxForSelect(dataJson,function(rs){
		showMsg('设置成功，2秒之后自动退出');
		timeout(2,function(){
			logoutCommon();
		});
		
	});
}




function run_showMsg20210423(isRun,name){
	if(isRun =="true" || isRun){
		setTimeout(function () {
	        var  envMsg2018 = "原账号是："+name;
	        envMsg2018 += "&nbsp;&nbsp;<a href='javascript:run_revoke20210423();' style='color:#f6a201;cursor:pointer;'>🔙返回</a>";
	        var html_envMsg2018 = "<div id='env20180608' style='position:fixed;bottom:0;background:rgba(0,0,0);padding: 10px;right:1.2%;color:white;)'>"+envMsg2018+"</div>";
	        $("body").append(html_envMsg2018);
	    },1000);
	}
}

function run_revoke20210423(){
	ajaxForUpdate({apiUrl:"userInfo/run",action:"revoke"},function(){
		showMsg("操作成功");
		gotoPage("/admin");
	});
}
